<?php

namespace app\model\v1;

use app\BaseModel;
use think\exception\HttpException;

// 权限
class Auth extends BaseModel
{
    /**
     * 权限列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(): array
    {
        $authAll = $this->select();
        // 递归组装无限极权限菜单
        return recurrenceLevel($authAll->toArray(), 0);
    }

    /**
     * 权限详情
     * @param int $id
     * @return array|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info(int $id) {
        $authInfo = $this->find($id);
        if (!$authInfo) {
            throw new HttpException(404, '菜单信息不存在');
        }
        return $authInfo;
    }

    /**
     * 权限添加
     * @param array $postForm
     * @return bool
     */
    public function add(array $postForm): bool
    {
        return $this->save($postForm);
    }

    /**
     * 权限编辑
     * @param array $postForm
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit(array $postForm): bool
    {
        $auth = $this->find($postForm['id']);
        return $auth->save($postForm);
    }

    /**
     * 上线或下线 父级子级也会修改
     * @param int $id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changeStatus(int $id): bool
    {
        $curAuth = $this->info($id);
        if ($curAuth->getAttr('status') == 1) {
            // 下线时 只需下线当前权限及子级
            // 基于当前id作为父id 查找所有子级id
            $childAuthIds = $this->where('pid', $id)->column('id');
            array_push($childAuthIds, $id);
            return $this->whereIn('id', $childAuthIds)->save(['status' => 0]);
        } else {
            // 上线时 包括自身及父级也要上线
            // 基于当前权限的父id 递归向上查找所有的父id（含当前id）
            $parentAuthIds = $this->getParentAuthIds($id);
            return $this->whereIn('id', $parentAuthIds)->save(['status' => 1]);
        }
    }

    /**
     * 基于当前权限的父id 递归向上查找所有的父id（含当前id）
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getParentAuthIds($id): array
    {
        $curAuth = $this->info($id);
        $pIds = [];
        if ($curAuth->getAttr('pid') != 0) {
            $pIds = $this->getParentAuthIds($curAuth->getAttr('pid'));
        }
        $pIds[] = $id;
        return $pIds;
    }


}